package com.dong.rabbitmq.deadqueue;

import com.dong.rabbitmq.utils.RabbitMqUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dongjian
 * 死信队列-消费者01
 */
public class Consumer01 {

    /**
     * 普通交换机
     */
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    /**
     * 死信交换机
     */
    public static final String DEAD_EXCHANGE = "dead_exchange";
    /**
     * 普通队列
     */
    public static final String NORMAL_QUEUE = "normal_queue";
    /**
     * 死信队列
     */
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtil.getChannel();
        // 声明普通交换机和死信交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        /**
         * 普通队列arguments参数
         */
        Map<String, Object> argumentsMap = new HashMap<>(16);
        // 设置消息的存活时间-超过时间即转发到死信队列 10000ms=10s
        // argumentsMap.put("x-message-ttl", 10000);此处可在消息生产者方设置，更加灵活
        // 无法消费的消息 转发到死信队列的交换机
        argumentsMap.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // 死信队列routingKey
        argumentsMap.put("x-dead-letter-routing-key", "lisi");
        // 2.正常队列的长度 超过长度则转发到死信队列
         argumentsMap.put("x-max-length", 6);
        // 声明普通队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, argumentsMap);
        // 声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        // 绑定
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");
        System.out.println("等待接收消息......");

        // 消息处理
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), "UTF-8");

            if ("info-5".equals(msg)) {
                // 拒绝接收
                System.out.println("Consumer01接收消息是：" + msg + "：此消息被拒绝了");
                /**
                 * 参数1：消息标识
                 * 参数2：是否放回原队列：false否 true是
                 */
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println("Consumer01接收消息是：" + msg);
                /**
                 * 消息确认
                 * 参数1：消息标识
                 * 参数2：是否批量确认 false否 true是
                 */
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }

        };
        // 接收消息 autoAck-false 手动应答
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, consumerTag -> {
        });

    }
}
